import vue from '@vitejs/plugin-vue'
import fs from 'node:fs'
import { fileURLToPath, URL } from 'node:url'
import path from 'path'
import { defineConfig, loadEnv } from 'vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import vueDevTools from 'vite-plugin-vue-devtools'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')

  return {
    // 生成相对资源路径，支持直接打开 dist/index.html
    base: './',
    plugins: [
      vue(),
      vueDevTools(),
    // 构建完成后将 dist 复制到第二个输出目录
    {
      name: 'multi-out-copy',
      closeBundle() {
        const srcDir = path.resolve(process.cwd(), 'dist')
        const targetDir = '/Users/jago/Documents/trae_projects/electron_demo/dist'

        // 递归复制目录
        const copyRecursiveSync = (src: string, dest: string) => {
          const entries = fs.readdirSync(src, { withFileTypes: true })
          for (const entry of entries) {
            const srcPath = path.join(src, entry.name)
            const destPath = path.join(dest, entry.name)
            if (entry.isDirectory()) {
              fs.mkdirSync(destPath, { recursive: true })
              copyRecursiveSync(srcPath, destPath)
            } else if (entry.isSymbolicLink()) {
              const link = fs.readlinkSync(srcPath)
              fs.symlinkSync(link, destPath)
            } else {
              fs.copyFileSync(srcPath, destPath)
            }
          }
        }

        // 清空并创建目标目录，然后复制
        try {
          if (fs.existsSync(targetDir)) {
            fs.rmSync(targetDir, { recursive: true, force: true })
          }
          fs.mkdirSync(targetDir, { recursive: true })
          copyRecursiveSync(srcDir, targetDir)
          console.log(`[multi-out-copy] Build artifacts copied to: ${targetDir}`)
        } catch (err) {
          console.error('[multi-out-copy] Failed to copy build artifacts:', err)
        }
      }
    },
    /**
     * SVG 图标插件配置
     * 用于将 SVG 文件转换为可复用的图标组件
     */
    createSvgIconsPlugin({
      // 指定需要缓存的图标文件夹
      iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
      // 指定symbolId格式
      symbolId: 'icon-[dir]-[name]',
      // 自定义插入位置
      inject: 'body-last',
      // 自定义DOM id
      customDomId: '__svg__icons__dom__',
    }),

  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
  // 配置scss全局变量
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "@/styles/variables.scss" as *;`,
      },
    },
  },
  server: {
    proxy: {
      '/api': {
        target: env.VITE_API_SERVER_URL,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
      '/file': {
        target: env.VITE_API_SERVER_URL,
        changeOrigin: true,
        // 保持 /file 路径，不要移除
        // rewrite: (path) => path.replace(/^\/file/, ''),
      }
    }
  },
  build: {
    // Vite 仅支持单 outDir，这里设置为主输出目录
    outDir: 'dist',
    rollupOptions: {
      output: {
        /**
         * 手动配置代码分割，将大型依赖库分离到独立的chunk中
         * 这样可以有效减少单个chunk的大小，提高加载性能
         */
        manualChunks: {
          // 将Vue相关库分离到vendor-vue chunk
          'vendor-vue': ['vue', 'vue-router', 'pinia'],
          // 将Element Plus组件库分离到vendor-element chunk
          'vendor-element': ['element-plus'],
          // 将Element Plus图标分离到vendor-icons chunk
          'vendor-icons': ['@element-plus/icons-vue'],
        }
      }
    },
    // 调整chunk大小警告阈值到1MB，避免不必要的警告
    chunkSizeWarningLimit: 1000
  }
  }
})
